﻿using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Utils;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;


namespace DepartmentWork.Platform.Areas.PerationAndMaintenanceArea.Controllers
{
    public class MaintenanceController : BaseController
    {





        #region 运维项目方法

        //
        // GET: /PerationAndMaintenanceArea/Maintenance/

        /// <summary>
        /// 运维工作列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Maintenance(string flag = "", string info = "")
        {
            ViewBag.CreateProjectFlag = flag;
            ViewBag.Info = info;

            #region 设置分页

            var pageSizeExecute = this.Request["pageSizeExecute"] == null ? 10 : int.Parse(Request["pageSizeExecute"]);
            var pageIndexExecute = this.Request["pageIndexExecute"] == null ? 1 : int.Parse(Request["pageIndexExecute"]);

            ViewData["pageIndexExecute"] = pageIndexExecute;
            ViewData["pageSizeExecute"] = pageSizeExecute;

            var pageSize = this.Request["pageSizeFinish"] == null ? 10 : int.Parse(Request["pageSizeFinish"]);
            var pageIndex = this.Request["pageIndexFinish"] == null ? 1 : int.Parse(Request["pageIndexFinish"]);

            ViewData["pageIndexFinish"] = pageIndex;
            ViewData["pageSizeFinish"] = pageSize;

            #endregion
        
            MaintenanceWorkState model = new MaintenanceWorkState();
            model.ManintenanceNO = new DataSet();
            model.ManintenanceYES = new DataSet();
            IList<PROJECT_MAINTENANCE_APPOPS> MaintenanceYes = new List<PROJECT_MAINTENANCE_APPOPS>();//下线
            IList<PROJECT_MAINTENANCE_APPOPS> MaintenanceNO = new List<PROJECT_MAINTENANCE_APPOPS>();//进行中
            PROJECT_MAINTENANCE_APPOPS_USER user = new PROJECT_MAINTENANCE_APPOPS_USER();//人员关联表
            if (CurrentUser.UserID.Length != 0)
            {
                Guid selctid = new Guid(CurrentUser.UserID);
                Guid teamSpaceId = userTeamsapceRepository.GetModel(r => r.USER_ID == new Guid(CurrentUser.UserID)).FirstOrDefault().TEAMSPACE_ID;//获取团队空间ID
                MaintenanceYes = projectMaintenanceAppopsRepository.GetModel(a => a.TEAMSPACE_ID == teamSpaceId && a.APPOPS_STATE == "1").OrderByDescending(r => r.APPOPS_TIME).ToList();//下线
                MaintenanceNO = projectMaintenanceAppopsRepository.GetModel(a => a.TEAMSPACE_ID == teamSpaceId && a.APPOPS_STATE == "0").OrderByDescending(r => r.APPOPS_TIME).ToList();//进行中

                Guid myid = new Guid(CurrentUser.UserID);
                var myname = userRepository.Find(r => r.USER_ID == myid).DISPLAY_NAME.ToString();//要权限
                ViewBag.myName = myname;//获取到登录人的姓名返回给界面用于锁定发布人
                ViewBag.NAMEID = selctid;
                #region 获取该团队空间下的全部人员
                List<UserInfoViewModel> userList = new List<UserInfoViewModel>();
                List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId).ToList();
                userList.AddRange((from item in userTeams
                                   select new UserInfoViewModel()
                                   {
                                       UserId = item.USER_ID
                                   }).ToList());
                for (int i = 0; i < userList.Count(); i++)
                {
                    var id = userList[i].UserId;
                    userList[i].UserName = userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
                }
                TempData["UserList"] = userList;
                #endregion

                #region 校验身份 是否是团队负责人
                ViewBag.IsAdmin = false;
                string[] pathArr = Request.Path.Split('/');
                Guid userGuid = new Guid(CurrentUser.UserID);//找到用户登录ID
                USER_INFO userinfo = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();//根据用户登录ID 通过员工表 查出此员工信息
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == userinfo.USER_ID).FirstOrDefault();//根据员工的ID 通过团队空间表  查出此人的团队空间信息
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();//根据此人全队空间表信息的团队空间权限ID，查出此人在权限表的信息
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();//根据此人在权限表的信息中的权限ID，查出此人的菜单表信息
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();//根据菜单Id找此人菜单表的所有信息
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                    {
                        ViewBag.IsAdmin = true;
                        break;
                    }
                }
                #endregion

                #region 校验该登录用户所有负责的项目 返回前台判断是否能在界面新增运维记录
                if (CurrentUser.UserID.Length != 0)
                {
                    List<ProjectManintenanceAppopsViewModel> aplist = new List<ProjectManintenanceAppopsViewModel>();
                    
                    Guid userF = new Guid(CurrentUser.UserID);
                    USER_INFO userInfo = userRepository.GetModel(r => r.USER_ID == userF).FirstOrDefault();
                    List<PROJECT_MAINTENANCE_APPOPS_USER> developUser = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_PRINCIPAL_USER_ID == userInfo.USER_ID).ToList();
                    if (developUser.Count>0)
                    {
                        foreach (PROJECT_MAINTENANCE_APPOPS_USER ap in developUser)
                        {
                            ProjectManintenanceAppopsViewModel pm = new ProjectManintenanceAppopsViewModel();
                            PROJECT_MAINTENANCE_APPOPS app = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == ap.APPOPS_APPOPS_ID).FirstOrDefault();
                            pm.appops_id = app.APPOPS_ID;
                            aplist.Add(pm);
                        }
                    }
                    ViewBag.currentUser = aplist;
                }
               
                #endregion




            }
            else//如果是匿名用户
            {
                ViewBag.IsAdmin = false;
                MaintenanceNO = projectMaintenanceAppopsRepository.GetModel(a => a.APPOPS_STATE == "0").OrderByDescending(r => r.APPOPS_TIME).ToList();//进行中
                MaintenanceYes = projectMaintenanceAppopsRepository.GetModel(a => a.APPOPS_STATE == "1").OrderByDescending(r => r.APPOPS_TIME).ToList();//下线
            }
            model.ManintenanceNO = DataSetHelp.Instance.ToDataSet(MaintenanceNO);
            model.ManintenanceYES = DataSetHelp.Instance.ToDataSet(MaintenanceYes);
            #region 根据工作ID 和 关联人员表，查找出多名负责人的名字
            model.ManintenanceNO.Tables[0].Columns.Add("appops_principal");
            model.ManintenanceYES.Tables[0].Columns.Add("appops_principall");
            for (int i = 0; i < model.ManintenanceNO.Tables[0].Rows.Count; i++)//根据已经查出的进行中的运维工作，进行遍历
            {
                var item = model.ManintenanceNO.Tables[0].Rows[i];//一个集合里进行中的运维工作
                Guid proId = new Guid(item["appops_id"].ToString());//根据这个工作 找出这个工作的项目ID
                List<PROJECT_MAINTENANCE_APPOPS_USER> username = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_APPOPS_ID == proId).ToList();//根据工作ID查出人员关联表中的对应所有负责人
                for (int j = 0; j < username.Count(); j++)//遍历每个关联人员信息
                {
                    Guid userId = username[j].APPOPS_PRINCIPAL_USER_ID;//查出每个关联人员信息的员工ID
                    item["appops_principal"] += userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME + " ";//根绝员工ID查员工表找出姓名
                }
            }



            for (int i = 0; i < model.ManintenanceYES.Tables[0].Rows.Count; i++)//根据已经查出的进行中的运维工作，进行遍历
            {
                var item = model.ManintenanceYES.Tables[0].Rows[i];//一个集合里进行中的运维工作
                Guid proId = new Guid(item["appops_id"].ToString());//根据这个工作 找出这个工作的项目ID
                List<PROJECT_MAINTENANCE_APPOPS_USER> username = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_APPOPS_ID == proId).ToList();//根据工作ID查出人员关联表中的对应所有负责人
                for (int j = 0; j < username.Count(); j++)//遍历每个关联人员信息
                {
                    Guid userId = username[j].APPOPS_PRINCIPAL_USER_ID;//查出每个关联人员信息的员工ID
                    item["appops_principall"] += userRepository.GetModel(r => r.USER_ID == userId).FirstOrDefault().DISPLAY_NAME + " ";//根据员工ID查员工表找出姓名
                }
            }
            #endregion


            ViewData["totalExecute"] = model.ManintenanceNO.Tables[0].Rows.Count;
            ViewData["totalFinish"] = model.ManintenanceYES.Tables[0].Rows.Count;
           
            return View(model);
        }


        /// <summary>
        /// 新增运维项目
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InserMaintenance(FormCollection collection)
        {
            try
            {

                string[] leadersArr = collection["select_WorkLeader"].Split(',');
                PROJECT_MAINTENANCE_APPOPS inser = new PROJECT_MAINTENANCE_APPOPS();
                PROJECT_MAINTENANCE_APPOPS_USER user = new PROJECT_MAINTENANCE_APPOPS_USER();
                inser.APPOPS_ID = Guid.NewGuid();
                foreach (string userId in leadersArr)
                {
                    Guid myid = new Guid(userId);
                    user.APPOPS_PRINCIPAL_USER_ID = new Guid(userId);
                    user.APPOPS_APPOPS_ID = inser.APPOPS_ID;
                    user.APPOPS_GL_ID = Guid.NewGuid();
                    projectMaintenanceAppopsUserRepository.Insert(user);
                }
             
                int count = 0;
                List<PROJECT_MAINTENANCE_APPOPS> NO = projectMaintenanceAppopsRepository.GetModel().ToList();
                if (NO == null)
                {
                    count = 1;
                }
                else
                {
                    count = NO.Count + 1;
                }

                inser.APPOPS_NO = "S" + DateTime.Now.Year + count.ToString().PadLeft(3, '0');
                inser.APPOPS_BUSINESSLINKMAN = collection["tb_appops_businesslinkman"];
                inser.APPOPS_BUSINESSTYPE = collection["tb_appops_yewuleixing"];
                inser.APPOPS_DEPARTMENT = collection["tb_appops_department"];
                inser.APPOPS_DESCRIBE = collection["tb_appops_describe"];
                inser.APPOPS_FREQUENCY = collection["tb_appops_frequency"];
                inser.APPOPS_NAME = collection["tb_appops_xiangmuname"];
                inser.APPOPS_OVERTIME = DateTime.Now;//初始结束时间和开始时间一样
                inser.APPOPS_QUANTITY = collection["tb_appops_quantity"];
                inser.APPOPS_RELEVANCENAME = collection["tb_appops_relevancename"];
                inser.APPOPS_RELEVANCEWAY = collection["tb_appops_relevanceway"];
                inser.APPOPS_STATE = "0";
                inser.APPOPS_TIME = DateTime.Now;
                inser.APPOPS_WORKRANK = collection["select_appops_workrank"];
                inser.APPOPS_RANK = collection["select_appops_rank"];
                inser.APPOPS_FOUNDER_ID = new Guid(CurrentUser.UserID);
                inser.TEAMSPACE_ID = teamspaceRepository.GetModel(r => r.TEAMSPACE_NAME == CurrentUser.Department).FirstOrDefault().TEAMSPACE_ID;
                projectMaintenanceAppopsRepository.Insert(inser);
              

                return RedirectToAction("Maintenance", "Maintenance", new { area = "PerationAndMaintenanceArea", flag = "True" });

            }
            catch (Exception ex)
            {
                return RedirectToAction("Maintenance", "Maintenance", new { area = "PerationAndMaintenanceArea", flag = "False", info = ex.Message });

            }



        }


        /// <summary>
        /// 运维项目详细信息
        /// </summary>
        /// <returns></returns>
        public ActionResult Particulars(string projectId, string flag = "", string flagInfo = "")
        {

            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;

            Guid workGuid = new Guid(projectId);
            PROJECT_MAINTENANCE_APPOPS work = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == workGuid).FirstOrDefault();
            ProjectManintenanceAppopsViewModel model = new ProjectManintenanceAppopsViewModel();
            var myname = userRepository.Find(r => r.USER_ID == work.APPOPS_FOUNDER_ID).DISPLAY_NAME.ToString(); //根据项目ID 中的创建人ID  找出人员表中的创建人姓名

            List<PROJECT_MAINTENANCE_APPOPS_USER> user = new List<PROJECT_MAINTENANCE_APPOPS_USER>();
            user = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_APPOPS_ID == workGuid).ToList();
            foreach (PROJECT_MAINTENANCE_APPOPS_USER x in user)//遍历关联人员信息
            {
                model.appops_principal += userRepository.GetModel(r => r.USER_ID == x.APPOPS_PRINCIPAL_USER_ID).FirstOrDefault().DISPLAY_NAME + " ";//将名字叠加赋值给model中的负责人
            }
            model.appops_businesslinkman = work.APPOPS_BUSINESSLINKMAN;
            model.appops_businesstype = work.APPOPS_BUSINESSTYPE;
            model.appops_department = work.APPOPS_DEPARTMENT;
            model.appops_describe = work.APPOPS_DESCRIBE;
            model.appops_frequency = work.APPOPS_FREQUENCY;
            model.appops_id = work.APPOPS_ID;
            model.appops_name = work.APPOPS_NAME;
            model.appops_overtime = work.APPOPS_OVERTIME;
            model.appops_phone = work.APPOPS_PHONE;
            model.appops_quantity = work.APPOPS_QUANTITY;
            model.appops_rank = work.APPOPS_RANK;
            model.appops_relevancename = work.APPOPS_RELEVANCENAME;
            model.appops_relevanceway = work.APPOPS_RELEVANCEWAY;
            model.appops_state = work.APPOPS_STATE;
            model.appops_time = work.APPOPS_TIME;
            model.appops_workrank = work.APPOPS_WORKRANK;
            model.appops_aaa = work.APPOPS_AAA;
            model.appops_founder = myname;
            model.appops_no = work.APPOPS_NO;
            if (work.APPOPS_STATE == "1")
            {
                model.appops_state = "已下线";
            }
            else
            {
                model.appops_state = "进行中";
            }
            if (CurrentUser.UserID.Length != 0)
            {
                #region 获取该团队空间下的全部人员
                Guid teamSpaceId = userTeamsapceRepository.GetModel(r => r.USER_ID == new Guid(CurrentUser.UserID)).FirstOrDefault().TEAMSPACE_ID;
                List<UserInfoViewModel> userList = new List<UserInfoViewModel>();
                List<USER_TEAMSAPCE> userTeams = userTeamsapceRepository.GetModel(r => r.TEAMSPACE_ID == teamSpaceId).ToList();
                userList.AddRange((from item in userTeams
                                   select new UserInfoViewModel()
                                   {
                                       UserId = item.USER_ID
                                   }).ToList());
                for (int i = 0; i < userList.Count(); i++)
                {
                    var id = userList[i].UserId;
                    userList[i].UserName = userRepository.GetModel(r => r.USER_ID == id).FirstOrDefault().DISPLAY_NAME;
                    foreach (PROJECT_MAINTENANCE_APPOPS_USER x in user)//遍历关联人员信息
                    {
                        if (userList[i].UserId == x.APPOPS_PRINCIPAL_USER_ID)//如果关联人员的ID和空间下某个人员ID相同，标记true，作为前台初始化的负责人员
                        {
                            userList[i].IsProjectLeader = "True";
                        }
                    }
                }
                TempData["UserList"] = userList;
                #endregion
                #region 校验身份 是否是团队负责人
                ViewBag.IsAdmin = false;
                string[] pathArr = Request.Path.Split('/');
                Guid userGuid = new Guid(CurrentUser.UserID);//找到用户登录ID
                USER_INFO userinfo = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();//根据用户登录ID 通过员工表 查出此员工信息
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == userinfo.USER_ID).FirstOrDefault();//根据员工的ID 通过团队空间表  查出此人的团队空间信息
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();//根据此人全队空间表信息的团队空间权限ID，查出此人在权限表的信息
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();//根据此人在权限表的信息中的权限ID，查出此人的菜单表信息
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();//根据菜单Id找此人菜单表的所有信息
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                    {
                        ViewBag.IsAdmin = true;
                        break;
                    }
                }
                #endregion

                #region 校验该登录用户所有负责的项目 是否是该项目的负责人
                USER_INFO userInfo = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
                List<PROJECT_MAINTENANCE_APPOPS_USER> developUser = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_PRINCIPAL_USER_ID == userInfo.USER_ID).ToList();
                if (developUser.Count > 0)
                {
                    ViewBag.FZ = false;
                    foreach (PROJECT_MAINTENANCE_APPOPS_USER ap in developUser)
                    {
                        if (ap.APPOPS_APPOPS_ID == workGuid)
                        {
                            ViewBag.FZ = true;
                        }
                    }
                }
                #endregion
            }
            return this.View(model);

        }



        /// <summary>
        /// 修改运维项目信息
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public ActionResult UpdateParticulars(FormCollection collection)
        {
            PROJECT_MAINTENANCE_APPOPS model = new PROJECT_MAINTENANCE_APPOPS();//实例化运维表
           
            try
            {
                model.APPOPS_ID = new Guid(collection["hid_appops_id"]);//运维表中的工作ID赋值
                PROJECT_MAINTENANCE_APPOPS old = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == model.APPOPS_ID).FirstOrDefault();//根据运维表ID找出所有该运维信息
                Guid projectId = new Guid(collection["hid_appops_id"]);//找到运维表ID
                List<PROJECT_MAINTENANCE_APPOPS_USER> cacheUser = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_APPOPS_ID == projectId).ToList();//根据运维ID 查找负责人员表信息
                projectMaintenanceAppopsUserRepository.BulkDelete(cacheUser);//删除之前所有该运维相关的 运维人员关联信息
                List<PROJECT_MAINTENANCE_APPOPS_USER> usermodel = new List<PROJECT_MAINTENANCE_APPOPS_USER>();//再实例化一个运维人员关联表
                string[] leadersArr = collection["select_WorkLeader"].Split(',');//获取前台新的负责人ID
                for (int i = 0; i < leadersArr.Length; i++)//遍历出所有新负责人ID
                {
                    PROJECT_MAINTENANCE_APPOPS_USER user = new PROJECT_MAINTENANCE_APPOPS_USER();
                    user.APPOPS_APPOPS_ID = projectId;
                    user.APPOPS_GL_ID = Guid.NewGuid();
                    user.APPOPS_PRINCIPAL_USER_ID = new Guid(leadersArr[i]);
                    usermodel.Add(user);
                }
                model.APPOPS_BUSINESSLINKMAN = collection["tb_appops_businesslinkman"] == "" ? old.APPOPS_BUSINESSLINKMAN : collection["tb_appops_businesslinkman"];
                model.APPOPS_BUSINESSTYPE = collection["tb_appops_businesstype"] == "" ? old.APPOPS_BUSINESSTYPE : collection["tb_appops_businesstype"];
                model.APPOPS_DEPARTMENT = collection["tb_appops_department"] == "" ? old.APPOPS_DEPARTMENT : collection["tb_appops_department"];
                model.APPOPS_DESCRIBE = collection["tb_appops_describe"] == "" ? old.APPOPS_DESCRIBE : collection["tb_appops_describe"];
                model.APPOPS_FREQUENCY = collection["tb_appops_frequency"] == "" ? old.APPOPS_FREQUENCY : collection["tb_appops_frequency"];
                model.APPOPS_NAME = collection["tb_appops_name"] == "" ? old.APPOPS_NAME : collection["tb_appops_name"];
                model.APPOPS_OVERTIME = old.APPOPS_OVERTIME;
                model.APPOPS_PHONE = old.APPOPS_PHONE;
                model.APPOPS_QUANTITY = collection["tb_appops_quantity"] == "" ? old.APPOPS_QUANTITY : collection["tb_appops_quantity"];
                model.APPOPS_RANK = collection["select_appops_rank"] == "" ? old.APPOPS_RANK : collection["select_appops_rank"];
                model.APPOPS_RELEVANCENAME = collection["tb_appops_relevancename"] == "" ? old.APPOPS_RELEVANCENAME : collection["tb_appops_relevancename"];
                model.APPOPS_RELEVANCEWAY = collection["tb_appops_relevanceway"] == "" ? old.APPOPS_RELEVANCEWAY : collection["tb_appops_relevanceway"];
                model.APPOPS_STATE = old.APPOPS_STATE;
                model.APPOPS_TIME = old.APPOPS_TIME;
                model.APPOPS_WORKRANK = collection["select_appops_workrank"] == "" ? old.APPOPS_WORKRANK : collection["select_appops_workrank"];
                model.APPOPS_FOUNDER_ID = old.APPOPS_FOUNDER_ID;
                model.APPOPS_NO = collection["tb_appops_no"] == "" ? old.APPOPS_NO : collection["tb_appops_no"];
                model.TEAMSPACE_ID = old.TEAMSPACE_ID;


                projectMaintenanceAppopsRepository.Update(model);
                projectMaintenanceAppopsUserRepository.BulkInsert(usermodel);//批量把新负责人 ID和 该运维工作ID  增加到相关负责人表中

                return RedirectToAction("Particulars", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.APPOPS_ID, flag = "True", flagInfo = "项目编辑成功！" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Particulars", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.APPOPS_ID, flag = "False", flagInfo = "项目编辑失败！" + ex.Message });
            }


        }




        /// <summary>
        /// 编辑工作状态
        /// </summary>
        /// <returns></returns>
        public ActionResult StateCompile(FormCollection collection)
        {
            Guid projectId = new Guid(collection["hid_appops_id"]);

            try
            {
                PROJECT_MAINTENANCE_APPOPS pro = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == projectId).FirstOrDefault();

                pro.APPOPS_STATE = collection["select_AppspsStatus"];
                pro.APPOPS_OVERTIME = DateTime.Now;
                projectMaintenanceAppopsRepository.Update(pro);
                return RedirectToAction("Particulars", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = projectId, flag = "True", flagInfo = "项目状态编辑完成！" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Particulars", "Maintenance", new { aarea = "PerationAndMaintenanceArea", projectId = projectId, info = ex.Message });
            }
        }



        #endregion




        #region 项目账号
        /// <summary>
        /// 项目账号编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult NumberCompile(FormCollection collection)
        {

            Guid projectId = new Guid(collection["hid_appops_id"]);
            try
            {
                PROJECT_MAINTENANCE_APPOPS pro = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == projectId).FirstOrDefault();

                pro.APPOPS_AAA = collection["tb_appops_aaa"];
                projectMaintenanceAppopsRepository.Update(pro);
                return RedirectToAction("Particulars", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = projectId, flag = "True", flagInfo = "项目账号编辑完成！" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Particulars", "Maintenance", new { aarea = "PerationAndMaintenanceArea", projectId = projectId, info = ex.Message });
            }
        }



        #endregion




        #region 运维记录

        /// <summary>
        /// 运维记录列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Reacord(string projectId, string flag = "", string flagInfo = "")
        {
            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;
            Guid workGuid = new Guid(projectId);
            List<PROJECT_MAINTENANCE_RECORD> RECORD = new List<PROJECT_MAINTENANCE_RECORD>();
            List<ProjectManintenanceRecordViewModel> record = new List<ProjectManintenanceRecordViewModel>();
            RECORD = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_OPERATION_ID == workGuid).OrderByDescending(r => r.RECORD_TIME).ToList();
            string name = projectMaintenanceAppopsRepository.Find(r => r.APPOPS_ID == workGuid).APPOPS_NAME.ToString();
            for (int i = 0; i < RECORD.Count; i++)
            {
                ProjectManintenanceRecordViewModel viewmodel = new ProjectManintenanceRecordViewModel();
                viewmodel.record_content = RECORD[i].RECORD_CONTENT;
                viewmodel.record_id = RECORD[i].RECORD_ID;
                viewmodel.record_name = RECORD[i].RECORD_NAME;
                viewmodel.record_operation_id = RECORD[i].RECORD_OPERATION_ID;
                viewmodel.record_operationtype = RECORD[i].RECORD_OPERATIONTYPE;
                viewmodel.record_time = RECORD[i].RECORD_TIME;
                viewmodel.record_accessory = RECORD[i].RECORD_ACCESSORY;
                viewmodel.record_operation_time = RECORD[i].RECORD_OPERATION_TIME;
                record.Add(viewmodel);
            }

            if (CurrentUser.UserID.Length != 0)
            {
             
                Guid myid = new Guid(CurrentUser.UserID);//找到用户登录ID
                ViewBag.NAMEID = myid;

                #region 校验身份 是否是团队负责人
                ViewBag.IsAdmin = false;
                string[] pathArr = Request.Path.Split('/');
                USER_INFO userinfo = userRepository.GetModel(r => r.USER_ID == myid).FirstOrDefault();//根据用户登录ID 通过员工表 查出此员工信息
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == userinfo.USER_ID).FirstOrDefault();//根据员工的ID 通过团队空间表  查出此人的团队空间信息
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();//根据此人全队空间表信息的团队空间权限ID，查出此人在权限表的信息
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();//根据此人在权限表的信息中的权限ID，查出此人的菜单表信息
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();//根据菜单Id找此人菜单表的所有信息
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                    {
                        ViewBag.IsAdmin = true;
                        break;
                    }
                }
                #endregion

                #region 校验该登录用户所有负责的项目 是否是该项目的负责人
                USER_INFO userInfo = userRepository.GetModel(r => r.USER_ID == myid).FirstOrDefault();
                List<PROJECT_MAINTENANCE_APPOPS_USER> developUser = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_PRINCIPAL_USER_ID == userInfo.USER_ID).ToList();
                if (developUser.Count > 0)
                {
                    ViewBag.FZ = false;
                    foreach (PROJECT_MAINTENANCE_APPOPS_USER ap in developUser)
                    {
                        if (ap.APPOPS_APPOPS_ID == workGuid)
                        {
                            ViewBag.FZ = true;
                        }
                    }
                }
                #endregion



            }
         

            ViewBag.Record = record;
            ViewBag.RecordName = name;
            ViewBag.ID = workGuid;
            return View();
        }


        /// <summary>
        /// 新增运维记录
        /// </summary>
        /// <returns></returns>
        public ActionResult Reacord_Insert(FormCollection collection)
        {

            try
            {
                Guid workGuid = new Guid(collection["hid_appops_id"]);//运维项目ID
                Guid NameGuid = new Guid(collection["hid_appops_name_id"]);//记录人ID
                string name = userRepository.GetModel(r => r.USER_ID == NameGuid).FirstOrDefault().DISPLAY_NAME;
                PROJECT_MAINTENANCE_RECORD inser = new PROJECT_MAINTENANCE_RECORD();
                FILEINFO fileModel = new FILEINFO();
                inser.RECORD_NAME = name;
                inser.RECORD_CONTENT = collection["tb_record_content"];
                inser.RECORD_ID = Guid.NewGuid();
                inser.RECORD_OPERATION_ID = workGuid;
                inser.RECORD_OPERATIONTYPE = collection["select_record_operationtype"];
                inser.RECORD_TIME = DateTime.Now;
                inser.RECORD_NAME_ID = NameGuid;
                inser.RECORD_OPERATION_TIME =Convert.ToDateTime(collection["selcet_text_DTime"]);
                #region
                string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Document\";//获取web.config下appsetting节点中UpLoadPath的值
                int fileCount = this.Request.Files.Count;//请求文件的个数
                HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];//获取对象HttpPostedFile （通过http协议用post方法上传来的文件）
                this.Request.Files.CopyTo(upFiles, 0);//将httppostedfile获取的fileCount的复制到数组
                if (upFiles[0].FileName != "")//如果文件的名字不是空的
                {
                    string fileSaveName = string.Empty;//声明一个字符串变量
                    HttpPostedFile hpf;//声明一个HttpPostedFile对象
                    hpf = upFiles[0];//将文件给hpf对象
                    string fullUpLoadPath = "";//声明一个字符串变量
                    Guid fileName = Guid.NewGuid();//创建一个guid（文件ID）
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));//拼一个路径（文件实际保存的名称）
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);//拼接上传路径
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));//保存到文件
                    fileModel.FILE_ID = fileName;
                    fileModel.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    fileModel.FILE_SAVEPATH = fullUpLoadPath;
                    fileModel.FILE_SAVENAME = fileSaveName;
                    fileModel.FILE_CREATETIME = DateTime.Now;
                    fileModel.FILE_CREATER = new Guid(CurrentUser.UserID);
                    fileModel.FILE_TYPE = "DEVELOP_TASKBOOK";
                    fileModel.CONTACT_ID = inser.RECORD_ID;
                    fileRepository.Insert(fileModel);
                }

                #endregion
                inser.RECORD_ACCESSORY = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1]; //附件名称
                projectMaintenanceRecordRepository.Insert(inser);
                return RedirectToAction("Reacord", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = workGuid, flagInfo = "新增记录成功！", flag = "True" });

            }
            catch (Exception ex)
            {
                Guid workGuid = new Guid(collection["hid_appops_id"]);
                return RedirectToAction("Reacord", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = workGuid, flag = "False", flagInfo = "新增记录失败！" + ex.Message });
            }
        }



        /// <summary>
        /// 修改运维记录
        /// </summary>
        /// <returns></returns>
        public ActionResult Reacord_updat(FormCollection collection)
        {
            PROJECT_MAINTENANCE_RECORD model = new PROJECT_MAINTENANCE_RECORD();
            model.RECORD_ID = new Guid(collection["td_appops_id"]);
            FILEINFO fileModel = new FILEINFO();
            PROJECT_MAINTENANCE_RECORD old = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_ID == model.RECORD_ID).FirstOrDefault();
            try
            {

                string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Document\";//获取web.config下appsetting节点中UpLoadPath的值
                int fileCount = this.Request.Files.Count;//请求文件的个数
                HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];//获取对象HttpPostedFile （通过http协议用post方法上传来的文件）
                this.Request.Files.CopyTo(upFiles, 0);//将httppostedfile获取的fileCount的复制到数组
                if (upFiles[0].FileName != "")//如果文件的名字不是空的
                {
                #region
                    try
                    {
                        FILEINFO oldFile = fileRepository.GetModel(r => r.CONTACT_ID == model.RECORD_ID).FirstOrDefault();
                        fileRepository.Delete(oldFile);
                    }
                    catch (Exception ex)
                    {
                        return RedirectToAction("Document", "Maintenance", new { area = "PerationAndMaintenanceArea", flag = "EditFalse", flagInfo = ex.Message, projectId = model.RECORD_ID });
                    }
                    string fileSaveName = string.Empty;//声明一个字符串变量
                    HttpPostedFile hpf;//声明一个HttpPostedFile对象
                    hpf = upFiles[0];//将文件给hpf对象
                    string fullUpLoadPath = "";//声明一个字符串变量
                    Guid fileName = Guid.NewGuid();//创建一个guid（文件ID）
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));//拼一个路径（文件实际保存的名称）
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);//拼接上传路径
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));//保存到文件

                    fileModel.FILE_ID = fileName;
                    fileModel.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    fileModel.FILE_SAVEPATH = fullUpLoadPath;
                    fileModel.FILE_SAVENAME = fileSaveName;
                    fileModel.FILE_CREATETIME = DateTime.Now;
                    fileModel.FILE_CREATER = new Guid(CurrentUser.UserID);
                    fileModel.FILE_TYPE = "DEVELOP_TASKBOOK";
                    fileModel.CONTACT_ID = model.RECORD_ID;
                    fileRepository.Insert(fileModel);
                    model.RECORD_ACCESSORY = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                }
                else//没有附件，用原来的
                {
                    model.RECORD_ACCESSORY = old.RECORD_ACCESSORY;
                }
                    #endregion
                model.RECORD_CONTENT = collection["tb_record_content"] == "" ? old.RECORD_CONTENT : collection["tb_record_content"];
                model.RECORD_NAME = old.RECORD_NAME; ;
                model.RECORD_OPERATION_ID = old.RECORD_OPERATION_ID;
                model.RECORD_OPERATIONTYPE = collection["select_record_operationtype"] == "" ? old.RECORD_OPERATIONTYPE : collection["select_record_operationtype"];
                model.RECORD_TIME = old.RECORD_TIME;
                model.RECORD_NAME_ID = old.RECORD_NAME_ID;
                model.RECORD_OPERATION_TIME = Convert.ToDateTime(collection["selcet_text_DTime"]);
                

                projectMaintenanceRecordRepository.Update(model);
                return RedirectToAction("Reacord", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.RECORD_OPERATION_ID, flagInfo = "修改记录成功！", flag = "True" });
            }
            catch (Exception ex)
            {

                return RedirectToAction("Reacord", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.RECORD_OPERATION_ID, flag = "False", flagInfo = "修改记录失败！" + ex.Message });
            }
        }

        /// <summary>
        /// 删除运维记录
        /// </summary>
        /// <returns></returns>
        public ActionResult Reacord_Delete(FormCollection collection)
        {
            PROJECT_MAINTENANCE_RECORD model = new PROJECT_MAINTENANCE_RECORD();
            model.RECORD_ID = new Guid(collection["delete_appops_idd"]);
            PROJECT_MAINTENANCE_RECORD old = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_ID == model.RECORD_ID).FirstOrDefault();
            FILEINFO fileModel = fileRepository.GetModel(r => r.CONTACT_ID == model.RECORD_ID).FirstOrDefault();
            try
            {
                model.RECORD_OPERATION_ID = old.RECORD_OPERATION_ID;
                projectMaintenanceRecordRepository.Delete(model);//根绝运维记录ID 删除这个记录
                if (fileModel != null)
                {
                    fileModel.CONTACT_ID = old.RECORD_ID;
                    fileRepository.Delete(fileModel);//删除该运维记录对应的运维记录附件
                }
                return RedirectToAction("Reacord", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.RECORD_OPERATION_ID, flagInfo = "记录删除成功！", flag = "True" });
            }
            catch (Exception ex)
            {

                return RedirectToAction("Reacord", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.RECORD_OPERATION_ID, flag = "False", flagInfo = "记录删除失败！" + ex.Message });
            }
        }

        /// <summary>
        /// ajax 获取一条运维记录信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult reacordUpdat(Guid roleId)
        {


            ProjectManintenanceRecordViewModel model = new ProjectManintenanceRecordViewModel();

            PROJECT_MAINTENANCE_RECORD role = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_ID == roleId).FirstOrDefault();

            model.record_content = role.RECORD_CONTENT;
            model.record_name = role.RECORD_NAME;
            model.record_operationtype = role.RECORD_OPERATIONTYPE;
            model.record_id = role.RECORD_ID;
            model.record_operation_id = role.RECORD_OPERATION_ID;
            model.record_operation_time_selcet = role.RECORD_OPERATION_TIME.ToString("yyyy-MM-dd");


            return Json(model);
        }



        /// <summary>
        /// ajax 获取一条运维项目的所有记录信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public string reacord_selcet(Guid roleId)
        {

            ProjectManintenanceRecordViewModel Model = new ProjectManintenanceRecordViewModel();

         
            List<PROJECT_MAINTENANCE_RECORD> role = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_OPERATION_ID == roleId).ToList();
            if (role.Count > 0) 
            {
                foreach (PROJECT_MAINTENANCE_RECORD r in role)
                {
                    //ProjectManintenanceRecordViewModel model = new ProjectManintenanceRecordViewModel();
                    //model.record_content = r.RECORD_CONTENT;
                    //model.record_name = r.RECORD_NAME;
                    //model.record_operationtype = r.RECORD_OPERATIONTYPE;
                    //model.record_id = r.RECORD_ID;
                    //model.record_operation_id = r.RECORD_OPERATION_ID;
                    //model.record_operation_time_selcet = r.RECORD_OPERATION_TIME.ToString("yyyy-MM-dd");
                    Model.All_rocord += "姓名：" + r.RECORD_NAME + " " + "操作时间：" + r.RECORD_OPERATION_TIME.ToString("yyyy-MM-dd") + " " + "内容：" + r.RECORD_CONTENT + "\r";

                }
                
            }



            return Model.All_rocord;
        }

        /// <summary>
        /// ajax 获取一条运维记录信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult reacord_id(Guid roleId)
        {


            ProjectManintenanceAppopsViewModel model = new ProjectManintenanceAppopsViewModel();

            PROJECT_MAINTENANCE_APPOPS role = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == roleId).FirstOrDefault();

            model.appops_id = role.APPOPS_ID;
            return Json(model);
        }





        /// <summary>
        /// ajax 获取要被删除的记录ID
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult reacordDelete(Guid roleId)
        {

            ProjectManintenanceRecordViewModel model = new ProjectManintenanceRecordViewModel();
            PROJECT_MAINTENANCE_RECORD role = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_ID == roleId).FirstOrDefault();
            model.record_id = role.RECORD_ID;
            return Json(model);
        }



        /// <summary>
        /// 下载的记录附件
        /// </summary>
        /// <param name="bugId"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetReacord(Guid bugId)
        {
            FILEINFO file = fileRepository.GetModel(r => r.CONTACT_ID == bugId).FirstOrDefault();
            ProjectBugViewModel model = new ProjectBugViewModel();

            if (file != null && file.FILE_ID.ToString().Trim() != "")
            {
                model.BugFileId = file.FILE_ID;
                model.BugFilePath = file.FILE_SAVEPATH;
                model.BugFileSaveName = file.FILE_SAVENAME;
                model.BugFileShowName = file.FILE_SHOWNAME;
            }
            else
            {
                model.BugFilePath = "";
                model.BugFileSaveName = "";
                model.BugFileShowName = "";
            }
            return this.Json(model);

        }




        #endregion


        #region 文档

        /// <summary>
        /// 文档列表
        /// </summary>
        /// <returns></returns>
        public ActionResult Document(string projectId, string flag = "", string flagInfo = "")
        {
            ViewBag.Flag = flag;
            ViewBag.FlagInfo = flagInfo;
            Guid workGuid = new Guid(projectId);
            List<PROJECT_MAINTENANCE_DOCUMENT> DOCUMENT = new List<PROJECT_MAINTENANCE_DOCUMENT>();
            List<ProjectMaintenanceDocumentViewModel> document = new List<ProjectMaintenanceDocumentViewModel>();
            DOCUMENT = projectMaintenanceDocumentRepository.GetModel(r => r.DOCUMENT_OPERATION_ID == workGuid).OrderByDescending(r => r.DOCUMENT_DATETIME).ToList();
            string name = projectMaintenanceAppopsRepository.Find(r => r.APPOPS_ID == workGuid).APPOPS_NAME.ToString();
            for (int i = 0; i < DOCUMENT.Count; i++)
            {
                ProjectMaintenanceDocumentViewModel viewmodel = new ProjectMaintenanceDocumentViewModel();
                viewmodel.document_id = DOCUMENT[i].DOCUMENT_ID;
                viewmodel.document_operation_id = DOCUMENT[i].DOCUMENT_OPERATION_ID;
                viewmodel.document_datetime = DOCUMENT[i].DOCUMENT_DATETIME;
                viewmodel.document_describe = DOCUMENT[i].DOCUMENT_DESCRIBE;
                viewmodel.document_founder = DOCUMENT[i].DOCUMENT_FOUNDER;
                viewmodel.document_accessory = DOCUMENT[i].RECORD_ACCESSORY;
                document.Add(viewmodel);
            }



            if (CurrentUser.UserID.Length != 0)
            {

                Guid myid = new Guid(CurrentUser.UserID);//找到用户登录ID
                ViewBag.NAMEID = myid;

                #region 校验身份 是否是团队负责人
                ViewBag.IsAdmin = false;
                string[] pathArr = Request.Path.Split('/');
                USER_INFO userinfo = userRepository.GetModel(r => r.USER_ID == myid).FirstOrDefault();//根据用户登录ID 通过员工表 查出此员工信息
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == userinfo.USER_ID).FirstOrDefault();//根据员工的ID 通过团队空间表  查出此人的团队空间信息
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();//根据此人全队空间表信息的团队空间权限ID，查出此人在权限表的信息
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();//根据此人在权限表的信息中的权限ID，查出此人的菜单表信息
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();//根据菜单Id找此人菜单表的所有信息
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == pathArr[3])
                    {
                        ViewBag.IsAdmin = true;
                        break;
                    }
                }
                #endregion

                #region 校验该登录用户所有负责的项目 是否是该项目的负责人
                USER_INFO userInfo = userRepository.GetModel(r => r.USER_ID == myid).FirstOrDefault();
                List<PROJECT_MAINTENANCE_APPOPS_USER> developUser = projectMaintenanceAppopsUserRepository.GetModel(r => r.APPOPS_PRINCIPAL_USER_ID == userInfo.USER_ID).ToList();
                if (developUser.Count > 0)
                {
                    ViewBag.FZ = false;
                    foreach (PROJECT_MAINTENANCE_APPOPS_USER ap in developUser)
                    {
                        if (ap.APPOPS_APPOPS_ID == workGuid)
                        {
                            ViewBag.FZ = true;
                        }
                    }
                }
                #endregion



            }









            ViewBag.Record = document;
            ViewBag.RecordName = name;
            ViewBag.ID = workGuid;
            return View();
        }


        /// <summary>
        /// 新增文档
        /// </summary>
        /// <returns></returns>
        public ActionResult inser_Document(FormCollection collection)
        {

            try
            {
                Guid workGuid = new Guid(collection["hid_document_id"]);
                PROJECT_MAINTENANCE_DOCUMENT inser = new PROJECT_MAINTENANCE_DOCUMENT();
                FILEINFO fileModel = new FILEINFO();
                //inser.RECORD_ACCESSORY = collection["tb_record_accessory"];
                inser.DOCUMENT_DATETIME = DateTime.Now;
                inser.DOCUMENT_DESCRIBE = collection["tb_document_describe"];
                inser.DOCUMENT_FOUNDER = collection["tb_document_founder"];
                inser.DOCUMENT_ID = Guid.NewGuid();
                inser.DOCUMENT_OPERATION_ID = workGuid;
                #region
                string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Document\";//获取web.config下appsetting节点中UpLoadPath的值
                int fileCount = this.Request.Files.Count;//请求文件的个数

                HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];//获取对象HttpPostedFile （通过http协议用post方法上传来的文件）
                this.Request.Files.CopyTo(upFiles, 0);//将httppostedfile获取的fileCount的复制到数组
                if (upFiles[0].FileName != "")//如果文件的名字不是空的
                {
                    string fileSaveName = string.Empty;//声明一个字符串变量
                    HttpPostedFile hpf;//声明一个HttpPostedFile对象
                    hpf = upFiles[0];//将文件给hpf对象
                    string fullUpLoadPath = "";//声明一个字符串变量
                    Guid fileName = Guid.NewGuid();//创建一个guid（文件ID）
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));//拼一个路径（文件实际保存的名称）
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);//拼接上传路径
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));//保存到文件
                    fileModel.FILE_ID = fileName;
                    fileModel.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    fileModel.FILE_SAVEPATH = fullUpLoadPath;
                    fileModel.FILE_SAVENAME = fileSaveName;
                    fileModel.FILE_CREATETIME = DateTime.Now;
                    fileModel.FILE_CREATER = new Guid(CurrentUser.UserID);
                    fileModel.FILE_TYPE = "DEVELOP_TASKBOOK";
                    fileModel.CONTACT_ID = inser.DOCUMENT_ID;
                    fileRepository.Insert(fileModel);
                }
                #endregion
                inser.RECORD_ACCESSORY = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                projectMaintenanceDocumentRepository.Insert(inser);
                return RedirectToAction("Document", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = workGuid, flagInfo = "新增文档成功！", flag = "True" });

            }
            catch (Exception ex)
            {
                Guid workGuid = new Guid(collection["hid_document_id"]);
                return RedirectToAction("Document", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = workGuid, flag = "False", flagInfo = "新增文档失败！" + ex.Message });
            }
        }

        /// <summary>
        /// 修改文档
        /// </summary> 
        /// <returns></returns>
        public ActionResult updat_Document(FormCollection collection)
        {
            PROJECT_MAINTENANCE_DOCUMENT model = new PROJECT_MAINTENANCE_DOCUMENT();
            model.DOCUMENT_ID = new Guid(collection["td_document_id"]);
            FILEINFO fileModel = new FILEINFO();
            PROJECT_MAINTENANCE_DOCUMENT old = projectMaintenanceDocumentRepository.GetModel(r => r.DOCUMENT_ID == model.DOCUMENT_ID).FirstOrDefault();
            try
            {
                #region
                string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Document\";//获取web.config下appsetting节点中UpLoadPath的值
                int fileCount = this.Request.Files.Count;//请求文件的个数
                HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];//获取对象HttpPostedFile （通过http协议用post方法上传来的文件）
                this.Request.Files.CopyTo(upFiles, 0);//将httppostedfile获取的fileCount的复制到数组
                if (upFiles[0].FileName != "")//如果文件的名字不是空的
                {
                    try
                    {
                        FILEINFO oldFile = fileRepository.GetModel(r => r.CONTACT_ID == model.DOCUMENT_ID).FirstOrDefault();
                        fileRepository.Delete(oldFile);
                    }
                    catch (Exception ex)
                    {
                        return RedirectToAction("Document", "Maintenance", new { area = "PerationAndMaintenanceArea", flag = "EditFalse", flagInfo = ex.Message, projectId = model.DOCUMENT_OPERATION_ID });
                    }

                    string fileSaveName = string.Empty;//声明一个字符串变量
                    HttpPostedFile hpf;//声明一个HttpPostedFile对象
                    hpf = upFiles[0];//将文件给hpf对象
                    string fullUpLoadPath = "";//声明一个字符串变量
                    Guid fileName = Guid.NewGuid();//创建一个guid（文件ID）
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));//拼一个路径（文件实际保存的名称）
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);//拼接上传路径
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));//保存到文件

                    fileModel.FILE_ID = fileName;
                    fileModel.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    fileModel.FILE_SAVEPATH = fullUpLoadPath;
                    fileModel.FILE_SAVENAME = fileSaveName;
                    fileModel.FILE_CREATETIME = DateTime.Now;
                    fileModel.FILE_CREATER = new Guid(CurrentUser.UserID);
                    fileModel.FILE_TYPE = "DEVELOP_TASKBOOK";
                    fileModel.CONTACT_ID = model.DOCUMENT_ID;
                    fileRepository.Insert(fileModel);
                    model.RECORD_ACCESSORY = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                }
                else//没有附件，用原来的
                {
                    model.RECORD_ACCESSORY = old.RECORD_ACCESSORY;
                }
                #endregion
                model.DOCUMENT_DATETIME = old.DOCUMENT_DATETIME;
                model.DOCUMENT_DESCRIBE = collection["tb_document_content"] == "" ? old.DOCUMENT_DESCRIBE : collection["tb_document_content"];
                model.DOCUMENT_FOUNDER = collection["tb_document_name"] == "" ? old.DOCUMENT_FOUNDER : collection["tb_document_name"];
                model.DOCUMENT_OPERATION_ID = old.DOCUMENT_OPERATION_ID;
                projectMaintenanceDocumentRepository.Update(model);
                return RedirectToAction("Document", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.DOCUMENT_OPERATION_ID, flagInfo = "修改文档成功！", flag = "True" });
            }
            catch (Exception ex)
            {
                return RedirectToAction("Document", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.DOCUMENT_OPERATION_ID, flag = "False", flagInfo = "修改文档失败！" + ex.Message });
            }
        }

        /// <summary>
        /// 删除文档
        /// </summary>
        /// <returns></returns>
        public ActionResult delete_Document(FormCollection collection)
        {

            PROJECT_MAINTENANCE_DOCUMENT model = new PROJECT_MAINTENANCE_DOCUMENT();
            model.DOCUMENT_ID = new Guid(collection["delete_document_idd"]);
            PROJECT_MAINTENANCE_DOCUMENT old = projectMaintenanceDocumentRepository.GetModel(r => r.DOCUMENT_ID == model.DOCUMENT_ID).FirstOrDefault();
            FILEINFO fileModel = fileRepository.GetModel(r => r.CONTACT_ID == model.DOCUMENT_ID).FirstOrDefault();
            try
            {
                model.DOCUMENT_OPERATION_ID = old.DOCUMENT_OPERATION_ID;
                projectMaintenanceDocumentRepository.Delete(model);
                if (fileModel != null)
                {
                    fileModel.CONTACT_ID = old.DOCUMENT_ID;
                    fileRepository.Delete(fileModel);
                }
                return RedirectToAction("Document", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.DOCUMENT_OPERATION_ID, flagInfo = "文档删除成功！", flag = "True" });
            }
            catch (Exception ex)
            {

                return RedirectToAction("Document", "Maintenance", new { area = "PerationAndMaintenanceArea", projectId = model.DOCUMENT_OPERATION_ID, flag = "False", flagInfo = "文档删除失败！" + ex.Message });
            }

        }


        /// <summary>
        /// ajax 获取一条文档信息
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult documentUpdat(Guid roleId)
        {
            ProjectMaintenanceDocumentViewModel model = new ProjectMaintenanceDocumentViewModel();
            PROJECT_MAINTENANCE_DOCUMENT role = projectMaintenanceDocumentRepository.GetModel(r => r.DOCUMENT_ID == roleId).FirstOrDefault();
            model.document_founder = role.DOCUMENT_FOUNDER;
            model.document_describe = role.DOCUMENT_DESCRIBE;
            model.document_id = role.DOCUMENT_ID;
            model.document_accessory = role.RECORD_ACCESSORY;
            return Json(model);
        }

        /// <summary>
        /// ajax 获取要被删除的文档ID
        /// </summary>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public JsonResult documentDelete(Guid roleId)
        {

            ProjectMaintenanceDocumentViewModel model = new ProjectMaintenanceDocumentViewModel();
            PROJECT_MAINTENANCE_DOCUMENT role = projectMaintenanceDocumentRepository.GetModel(r => r.DOCUMENT_ID == roleId).FirstOrDefault();
            model.document_id = role.DOCUMENT_ID;
            return Json(model);
        }






        /// <summary>
        /// 下载的文档附件
        /// </summary>
        /// <param name="bugId"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetDocument(Guid bugId)
        {
            FILEINFO file = fileRepository.GetModel(r => r.CONTACT_ID == bugId).FirstOrDefault();
            ProjectBugViewModel model = new ProjectBugViewModel();

            if (file != null && file.FILE_ID.ToString().Trim() != "")
            {
                model.BugFileId = file.FILE_ID;
                model.BugFilePath = file.FILE_SAVEPATH;
                model.BugFileSaveName = file.FILE_SAVENAME;
                model.BugFileShowName = file.FILE_SHOWNAME;
            }
            else
            {
                model.BugFilePath = "";
                model.BugFileSaveName = "";
                model.BugFileShowName = "";
            }
            return this.Json(model);

        }




        #endregion

    }
}
